/*
 * RentalReturnGUI.java
 *
 * Created on April 2, 2007, 9:49 AM
 */

package edu.byu.isys413.jjenkins.view;

import edu.byu.isys413.jjenkins.data.*;
import java.sql.Date;
import javax.swing.JOptionPane;

/**
 * The form processes the rental return
 * @author Rental are turned in with their respective SKU provided at the time of rental
 */
public class RentalReturnGUI extends javax.swing.JFrame {
    
    private static RentalReturnGUI instance = null;
    
    /** Creates new form RentalReturnGUI */
    public RentalReturnGUI() {
        initComponents();
                this.setLocationRelativeTo(null);
    }
    
    /** implements singleton pattern to insure that only one instance of this
     * gui is created*/
    
    public static synchronized RentalReturnGUI getInstance() {
        
        if (instance == null) {
            instance = new RentalReturnGUI();
        }
        
        return instance;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jToggleButton1 = new javax.swing.JToggleButton();
        jPanel14 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtSKU = new javax.swing.JTextField();
        btnreturn = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        btnDone = new javax.swing.JButton();

        jToggleButton1.setText("jToggleButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jPanel3.setMinimumSize(new java.awt.Dimension(30, 33));
        jPanel3.setPreferredSize(new java.awt.Dimension(430, 75));
        jLabel1.setText("Enter SKU of Rental Item:");
        jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(0, 0, 0)));
        jLabel1.setPreferredSize(new java.awt.Dimension(400, 15));
        jPanel3.add(jLabel1);

        jLabel3.setText("SKU:");
        jPanel3.add(jLabel3);

        txtSKU.setPreferredSize(new java.awt.Dimension(100, 20));
        jPanel3.add(txtSKU);

        btnreturn.setText("Return Item");
        btnreturn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnreturnActionPerformed(evt);
            }
        });

        jPanel3.add(btnreturn);

        jPanel14.add(jPanel3);

        jPanel1.setMinimumSize(new java.awt.Dimension(83, 50));
        jPanel1.setPreferredSize(new java.awt.Dimension(100, 100));
        btnDone.setText("Done");
        btnDone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDoneActionPerformed(evt);
            }
        });

        jPanel1.add(btnDone);

        jPanel14.add(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnDoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDoneActionPerformed
// TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnDoneActionPerformed
    
    private void btnreturnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnreturnActionPerformed
// TODO add your handling code here:
        try{
            String serNum = txtSKU.getText();
            String[] sku = serNum.split("pr", 2);
            String phys = PhysicalDAO.getInstance().getBySerialNum(sku[1]).getId();
            ForRentBO forRent = (ForRentBO)((ForRentDAO)ForRentDAO.getInstance()).read(phys);
            String curRental = forRent.getCurrentRentalID();
            ((ForRentDAO)ForRentDAO.getInstance()).save(forRent);
            RentalBO rental = (RentalBO)((RentalDAO)RevenueSourceFactory.getInstance().getDAO("rental")).read(curRental);
            rental.createDescription();
            RentalReturnBO rentalRet = RentalReturnDAO.getInstance().create();
            rentalRet.setDateIn(new Date(System.currentTimeMillis()));
            rentalRet.setRental(rental);
            RentalReturnDAO.getInstance().save(rentalRet);
            int daysOverdue = 0;
            daysOverdue = rental.calcDaysOverdue();
            if(daysOverdue > 0){
                FeeBO fee = (FeeBO)((FeeDAO)RevenueSourceFactory.getInstance().getDAO("fee")).create();
                fee.setRental(rental);
                fee.setEmployee(EmployeeDAO.getInstance().read("emp1"));
                fee.setDescription(fee.createDescription());
                FeeDAO.getInstance().save(fee);
                LateBO late = (LateBO)LateDAO.getInstance().create();
                late.setId(fee.getId());
                late.setDaysLate(daysOverdue);
                late.createDescription();
                String conceptualID = ((PhysicalBO)PhysicalDAO.getInstance().read(forRent.getId())).getConceptual().getId();
                double pricePerDay = (((ConceptualRentalBO)ConceptualRentalDAO.getInstance().read(conceptualID))).getLateFeePerDay();
                double price = (double)daysOverdue * pricePerDay;
                late.setPrice(price);
                late.setDaysLate(daysOverdue);
                fee.setAmount(price);
                fee.setPrice(price);
                fee.setQuantity(daysOverdue);
                
                FeeDAO.getInstance().save(fee);
                //LateDAO.getInstance().save(late);
                
                TransactionBO trans = TransactionDAO.getInstance().create();
                
                TransactionLineBO line = TransactionLineDAO.getInstance().create();
                line.setRevenueSource(fee);
                line.setTransaction(trans);
                trans.setType("fee");
                trans.setDate(new Date(System.currentTimeMillis()));
                trans.setStatus("pending");
                trans.addTransactionLine(line);
                CustomerBO cust = forRent.getCurrentRental().getLine().getTransaction().getCustomer();
                trans.setCustomer(cust);
                PaymentBO pay = PaymentDAO.getInstance().create();
                
                trans.setCurrentOpts(CurrentOptsDAO.getInstance().read("curr1"));
                trans.endTransaction();
                double total = trans.getTotal();
                pay.setAmount(total);
                pay.setType("credit");
                trans.setPayment(pay);
                
                trans.display();
                pay.setTransaction(trans);
                
                //forRent.setCurrentRentalID(null);
                ForRentDAO.getInstance().save(forRent);
                TransactionDAO.getInstance().save(trans);
                PaymentDAO.getInstance().save(pay);
                
                JOptionPane.showMessageDialog(null, "Late fee charged to " + cust.getFirstName() + " " + cust.getLastName() +
                        "\nAmount: $" + total);
            }
        }catch(DataException e){
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnreturnActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RentalReturnGUI().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDone;
    private javax.swing.JButton btnreturn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JTextField txtSKU;
    // End of variables declaration//GEN-END:variables
    
}
